package com.m1905hd.user.web.controller

import com.m1905hd.common.global.JSONCode
import com.m1905hd.common.util.Page
import com.m1905hd.user.service.LogoService
import com.m1905hd.user.web.PKUtil
import com.mongodb.BasicDBObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam

/**
 * Created with IDEA
 * User:hxh
 * Date:16/4/19
 * Time:上午10:24
 */
@Controller
@RequestMapping("logo")
class LogoController {

    @Autowired
    LogoService logoService

    @RequestMapping("list")
    def showList() {
        return "logo/list"
    }

    @RequestMapping(value = "/list.json")
    def list(
            @RequestParam(defaultValue = "15") int limit,
            @RequestParam(defaultValue = "0") int pageIndex,
            String title, int type
    ) {
        pageIndex = pageIndex + 1
        def list = new ArrayList()
        def query = new BasicDBObject()
        if (!StringUtils.isEmpty(title)) {
            query.append("title", ~/${title}/)
        }
        if (type != -1) {
            query.append("type", type)
        }
        Page page = this.logoService.list(query, new BasicDBObject("sort", 1), null, pageIndex, limit)
        page.data.each {
            it.status = it.status as String
            list.add(it)
        }
        [results: page.count, rows: list]
    }


    @RequestMapping(value = "edit", method = RequestMethod.POST)
    def edit(
            @RequestParam(defaultValue = "0") int id, String title, int status, String img,
            @RequestParam(defaultValue = "") String url, String open, int type
    ) {
        def obj = [title: title, status: status, img: img, url: url, open: open, type: type] as BasicDBObject
        if (id == 0) {
            obj.created = System.currentTimeMillis()
            id = this.logoService.getCurrentId()
        }
        this.logoService.update(id, obj)
        return "redirect:list"
    }

    @RequestMapping("delete.json")
    def del(String ids) {
        PKUtil.buildIds(ids).each {
            this.logoService.del(it)
        }
        return [code: JSONCode.SUCCESS.code]
    }
}
